package ThreadLocal;

/**
 * @description:
 * @author: ChenYunChou
 * @time: 2021/5/17 2021
 */
public class ThreadLocalByInitExample {
    private static ThreadLocal<String> threadLocal = new ThreadLocal(){
        @Override
        protected String initialValue() {
            System.out.println("执行initialValue()");
            return "默认值";
        }
    };

    public static void main(String[] args) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                String threadName = Thread.currentThread().getName();
                System.out.println(threadName + "存入值:" + threadName);
                print(threadName);
            }
        };

        new Thread(runnable,"cyc-01").start();
        new Thread(runnable,"cyc-02").start();
    }

    private static void print(String threadName) {
        try {
            String s = threadLocal.get();
            System.out.println(threadName + "取出值:" + s);
        } finally {
            threadLocal.remove();
        }
    }
}
